package com.example.zhangruoyu_zoe.utils

import android.content.Context
import com.example.zhangruoyu_zoe.data.Student
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.*
import java.lang.reflect.Type
import java.util.*

class StudentManager(private val context: Context) {

    private val filename = "students.json"
    private val gson = Gson()

    fun saveStudents(students: List<Student>) {
        val file = File(context.filesDir, filename)
        val writer = FileWriter(file)
        gson.toJson(students, writer)
        writer.close()
    }

    fun loadStudents(): List<Student> {
        val file = File(context.filesDir, filename)
        if (!file.exists()) return emptyList()

        val reader = FileReader(file)
        val type: Type = object : TypeToken<List<Student>>() {}.type
        return gson.fromJson(reader, type)
    }
}